<style scoped lang="scss">
@import url('index2.scss');
</style>
<template>
  <div class="app-container">
    <!--新模版样式，日历样式-->
    <div class="topsearch">

      <el-row>
        <el-col :span="22" class="searchcol">
          <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
            <el-form-item label="排班医生" prop="dname">
              <el-input v-model="queryParams.dname" placeholder="请输入排班医生" clearable @keyup.enter="handleQueryNew" />
            </el-form-item>
                    <el-form-item label="排班科室" prop="kid">
              <!-- <el-input v-model="queryParams.kid" placeholder="请输入排班科室" clearable @keyup.enter="handleQuery" /> -->
              <el-select v-model="queryParams.deptcode" placeholder="请选择排班科室" clearable  @keyup.enter="handleQueryNew" 
                style="width:180px;">
                <el-option v-for="item in departmentList" :key="item.kid" :label="item.kname" :value="item.kid" />
              </el-select>
            </el-form-item>
            <el-form-item label="排班日期" prop="workDate">
              <!-- <el-input v-model="queryParams.workDate" placeholder="请输入排班日期" clearable @keyup.enter="handleQuery" /> -->
              <el-date-picker clearable v-model="queryParams.workDate" type="date" value-format="YYYY-MM-DD" @keyup.enter="handleQueryNew"
                placeholder="请选择排班日期" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="排班班次" prop="workType">
              <!-- <el-input v-model="queryParams.workType" placeholder="请输入排班班次" clearable @keyup.enter="handleQuery" /> -->
              <el-select v-model="queryParams.workType" placeholder="请选择排班班次" clearable style="width: 250px;" @keyup.enter="handleQueryNew">
                <el-option v-for="item in workTypeList" :key="item.sid"
                  :label="item.shitName+'('+item.startTime+'-'+item.endTime+')'" :value="item.sid" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button class="newButton" icon="Search" @click="handleQueryNew">搜索</el-button>
              <el-button icon="Refresh" @click="resetQueryNew">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>


      <div style="margin-top: 1rem;">
        <el-segmented v-model="mode" :options="weekOptions" style="margin-bottom: 1rem" @change="handleChangeWeek" />
      </div>

      <el-row>
        <el-col :span="22" class="rightcol">
          <div class="newbtn" @click="handleAdd" v-hasPermi="['system:schedules:add']">
            <img src="@/assets/images/add.svg" alt="">
            <span>新建</span>
          </div>
          <div class="newbtn" v-if="single == false" @click="handleUpdate" v-hasPermi="['system:schedules:edit']">
            <img src="@/assets/images/edit.svg" alt=""></img>
            <span>编辑</span>
          </div>
          <div class="newbtn" v-if="multiple == false" @click="handleDelete" v-hasPermi="['system:schedules:remove']">
            <img src="@/assets/images/del.svg" alt=""></img>
            <span>删除</span>
          </div>
          <div class="newbtn" @click="handleExport" v-hasPermi="['system:schedules:export']">
            <img src="@/assets/images/export.svg" alt=""></img>
            <span>导出</span>
          </div>
          <div class="newbtn" @click="getList">
            <img src="@/assets/images/refresh.svg" alt=""></img>
            <span>刷新</span>
          </div>
        </el-col>
      </el-row>
    </div>



    <el-table v-loading="loading" :data="newDoctorsList" @selection-change="handleSelectionChange">
      <el-table-column label="ID"fixed  width="55" align="center" prop="did" />
      <el-table-column label="医生名称" fixed max-width="120" align="center" prop="dname" />
      <el-table-column label="医生头像" fixed max-width="120" align="center" prop="dimage" >
        <template #default="scope">
          <image-preview :src="scope.row.dimage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="年龄" fixed max-width="55" align="center" prop="age" />
      <el-table-column label="医生工号" fixed max-width="120" align="center" prop="dno" />
      <el-table-column label="性别" fixed max-width="55" align="center" prop="dsex">
        <template #default="scope">
          <span v-if="scope.row.dsex == '0'">男</span>
          <span v-else-if="scope.row.dsex == '1'">女</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column label="所在院区" fixed max-width="65" align="center" prop="dhoscampus" />
      <el-table-column label="所在科室" fixed align="center" prop="deptcode" max-width="120">
        <template #default="scope">
          <span>{{departmentList.find(item => item.kid == scope.row.deptcode)?.kname || '未知'}}</span>
        </template>
      </el-table-column>
      <!-- 动态日期列 -->
      <el-table-column v-for="col in headerList" :key="col.date" :label="col.label"
        :class-name="col.isToday ? 'today-col' : ''" align="center" width="220px">
        <template #default="scope">
          <!-- 这里可以换成排班标签、按钮、拖拽等 -->
          <div class="cell-inner" @click.stop="handleClickCell(scope.row, col.date)">
            <!-- {{ col }} -->
            <!-- {{ col.date }}{{ scope.row.did}} -->
            <!-- key: {{ scope.row.did }}_{{ col.date }}<br> -->
            <!-- val: {{ scheduleMap[`${scope.row.did}_${col.date}`] }} -->
            <!-- 可能有多条排班 -->
            <div v-for="(pb, idx) in scheduleMap?.[`${scope.row.did}_${col.date}`] ?? []" :key="idx"
              class="cell-inner-item">
              <!-- {{ pb.workType }} -->
              <div>
                {{workTypeList.find(item => item.sid ===pb.workType)?.shitName || '-'}}
                <span>(
                  {{workTypeList.find(item => item.sid === pb.workType)?.startTime || '-'}} -
                  {{workTypeList.find(item => item.sid === pb.workType)?.endTime || '-'}}
                  )</span>
              </div>
              <div> {{ pb.roomList.find(item => item.cid === pb.roomNo)?.roomname || '-' }}-{{
                pb.workStatus==1?'正常':'停诊' }} </div>

            </div>
            <!-- 无排班 -->
            <div v-if="!scheduleMap?.[`${scope.row.did}_${col.date}`]?.length" class="none">
              休息
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />



    <!-- 添加或修改排班列表对话框 -->
    <el-dialog :title="title" v-model="open" width="50%" class="newDialog">
      <el-form ref="schedulesRef" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="排班年度" prop="workYear">
          <el-input v-model="form.workYear" placeholder="请输入排班年度" />
        </el-form-item> -->
        <el-form-item label="院区" prop="hospitalCode">
          <el-input v-model="form.hospitalCode" placeholder="请输入院区" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排班科室" prop="kid">
              <!-- <el-input v-model="form.kid" placeholder="请输入排班科室" /> -->
              <el-select v-model="form.kid" placeholder="请选择排班科室" clearable @change="getRoomList">
                <el-option v-for="item in departmentList" :key="item.kid" :label="item.kname" :value="item.kid" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排班诊室" prop="roomNo">
              <!-- <el-input v-model="form.roomNo" placeholder="请输入排班诊室" :disabled="disabledRoomNo" /> -->
              <el-select v-model="form.roomNo" placeholder="请选择排班诊室" clearable :disabled="disabledRoomNo">
                <el-option v-for="item in roomList" :key="item.cid" :label="item.roomname" :value="item.cid" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排班日期" prop="workDate">
              <!-- <el-input v-model="form.workDate" placeholder="请输入排班日期" /> -->
              <el-date-picker clearable v-model="form.workDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请输入排班日期" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排班班次" prop="workType">
              <!-- <el-input v-model="form.workType" placeholder="请输入排班班次" /> -->
              <el-select v-model="form.workType" placeholder="请选择排班班次" clearable>
                <el-option v-for="item in workTypeList" :key="item.sid"
                  :label="item.shitName+'('+item.startTime+'-'+item.endTime+')'" :value="item.sid" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="排班医生" prop="doctorCode">
              <el-transfer v-model="form.doctorCode" :props="{
                key: 'did',
                label: 'dname',
                value: 'did',
              }" filter-placeholder="请选择排班医生" :data="doctorList" :titles="['医生列表', '已选择医生']" />
            </el-form-item>

          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最多号源" prop="maxPatient">
              <el-input v-model="form.maxPatient" placeholder="请输入最多号源" type="number" min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="已约人数" prop="bookedNum">
              <el-input v-model="form.bookedNum" placeholder="请输入已约人数" type="number" min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="辐射安全活度" prop="maxActivityMbq">
              <el-input v-model="form.maxActivityMbq" placeholder="请输入辐射安全活度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排班人" prop="suser">
              <el-input v-model="form.suser" placeholder="请输入排班人" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排班状态" prop="workStatus">
              <el-select v-model="form.workStatus" placeholder="请选择排班状态" clearable>
                <el-option v-for="item in ha_schedules_status" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="排班备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入排班备注" type="textarea" :rows="6" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Schedules">
import { listSchedules, getSchedules, delSchedules, addSchedules, updateSchedules } from "@/api/system/schedules"
import { listDepartment } from "@/api/system/department"
import { listConsultingroom } from "@/api/system/consultingroom"
import { listSchtype } from "@/api/system/schtype"
import { listDoctors } from "@/api/system/doctors"
import useUserStore from '@/store/modules/user'
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')
const userStore = useUserStore()
// console.log(userStore.name)

const { proxy } = getCurrentInstance()

const { ha_schedules_status } = proxy.useDict('ha_schedules_status') //排班状态


const schedulesList = ref([]) //排版的数据表
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)  //排班医生的总人数@鲍小伟20251119
const title = ref("")
// 排班科室选择后，是否禁用排班诊室
const disabledRoomNo = ref(true)
// 排班科室选择后，根据科室查询诊室列表
const roomList = ref([])
// 排班科室选择后，根据科室查询班次列表
const workTypeList = ref([])


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workYear: null,
    workDate: null,
    workType: null,
    doctorCode: null,
    hospitalCode: null,
    kid: null,
    roomNo: null,
    maxPatient: null,
    bookedNum: null,
    workStatus: null,
    maxActivityMbq: null,
    suser: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

const newqueryParams = {
  pageNum: 1,
  pageSize: 1000,
}
// 获取科室列表
const departmentList = ref([])

const doctorList = ref([])  //获取的医生列表



//排班中，先获取医生的列表和分

const newDoctorsList = ref([])
const weekOptions = ref([
    {
    label: '上一周',
    value: 'weekprev'
  },

  {
    label: '本周',
    value: 'week'
  },
  {
    label: '下一周',
    value: 'weeknext'
  },
  {
    label: '本月',
    value: 'month'
  }
])
// 排班日期列表@鲍小伟20251119
const headerList = ref([])
const mode = ref('week')               // week | month
const baseDate = ref(dayjs())          // 基准日（周/月）

onMounted(async () => {
  //列出所有的科室
  getDepartmentList()
  //获取所有的班次
  getWorkTypeList()
  //获取医生的列表分页@鲍小伟20251119
  getAllDoctorList()
  //排班数据
  
  await getList()
  //排班日期列表@鲍小伟20251119
  buildHeader()
 //end
})
//点击单个的排班
function handleClickCell(row, date) {
  console.log(row, date)
}
//排班的数据表，做匹配@鲍小伟20251120
function parseDidList(str) {
  try { return JSON.parse(str || '[]') } catch { return [] }
}
/* 3. 生成医生-日期 Map<`${did}_${date}`, 排班对象> */
const scheduleMap = computed(() => {
  const map = {} // 每个 key 对应一个数组
  schedulesList.value.forEach((pb, idx) => {
    const didArr = parseDidList(pb.doctorCode)
    didArr.forEach(did => {
      const key = `${did}_${pb.workDate}`
      // ****** 改成数组 ******
      if (!map[key]) map[key] = []
      map[key].push(pb)
      // console.log(`[${idx}] 追加 key: ${key}`, pb)
    })
  })
  // console.table(map)
  return map
})
//切换视图
function handleChangeWeek(newVal, oldVal) {
  mode.value = newVal
  buildHeader()
}
//获取头部日期列表
/* 生成表头 */
function buildHeader() {
  const today = dayjs()                     // 今日基准
  const arr = []

  if (mode.value === 'weekprev') {
    const mon = baseDate.value.subtract(1, 'week').startOf('week')
    for (let i = 0; i < 7; i++) {
      const d = mon.add(i, 'day')
      arr.push({
        date: d.format('YYYY-MM-DD'),
        label: `${d.format('MM-DD')}\n${d.format('ddd')}`,
        isToday: d.isSame(today, 'day')   // ✅ 标记
      })
    }
  } else if (mode.value === 'weeknext') {
    const mon = baseDate.value.add(1, 'week').startOf('week')
    for (let i = 0; i < 7; i++) {
      const d = mon.add(i, 'day')
      arr.push({
        date: d.format('YYYY-MM-DD'),
        label: `${d.format('MM-DD')}\n${d.format('ddd')}`,
        isToday: d.isSame(today, 'day')
      })
    }
  } else if (mode.value === 'week') {
    const mon = baseDate.value.startOf('week')
    for (let i = 0; i < 7; i++) {
      const d = mon.add(i, 'day')
      // console.log(d)
      arr.push({
        date: d.format('YYYY-MM-DD'),
        label: `${d.format('MM-DD')}\n${d.format('ddd')}`,
        isToday: d.isSame(today, 'day')
      })
    }
  } else if (mode.value === 'month') {
    const start = baseDate.value.startOf('month')
    const end   = baseDate.value.endOf('month')
    let d = start
    while (d.isBefore(end) || d.isSame(end, 'day')) {
      arr.push({
        date: d.format('YYYY-MM-DD'),
        label: `${d.format('MM-DD')}\n${d.format('ddd')}`,
        isToday: d.isSame(today, 'day')
      })
      d = d.add(1, 'day')
    }
  }else if (mode.value === 'day') {
    // ****** 单独一天 ******
    const d = dayjs(queryParams.value.workDate)               // 用户选中的日期
    console.log(d)
    arr.push({
      date: d.format('YYYY-MM-DD'),
      label: `${d.format('MM-DD')}\n${d.format('ddd')}`,
      isToday: d.isSame(today, 'day')
    })
  } 
  headerList.value = arr
}

//获取所有的医生列表和分页@鲍小伟20251119
function getAllDoctorList() {
 //可能需要传递一个月度参数，来查询该月的医生排班@鲍小伟20251119
  // queryParams.value.workDate = baseDate.value.format('YYYY-MM')

 loading.value = true
  listDoctors(queryParams.value).then(response => {
    // 计算年龄鲍小伟
    response.rows.forEach(item => {
      item.age = proxy.$filters.age(item.dbirthday)
    })
    newDoctorsList.value = response.rows
    total.value = response.total
    loading.value = false
  })

}
//监听科室的选择，如果有选择科室了，就查询医生
watch(() => form.value.kid, (newVal, oldVal) => {
  if(newVal){
    getDoctorList()
  }
})


//获取一下排班的医生,要按照科室来选择@鲍小伟1117
function getDoctorList() {
  const newqueryParamsDoctor = {
    pageNum: 1,
    pageSize: 1000,
    deptcode: form.value.kid,
  }
  listDoctors(newqueryParamsDoctor).then(response => {
    console.log(response)
    if(response.code == 200){
      doctorList.value = response.rows
    } else {
      doctorList.value = []
    }
  })
}

// function getDoctorListNew(kid) {
//   const newqueryParamsDoctor = {
//     pageNum: 1,
//     pageSize: 1000,
//     deptcode: kid,
//   }
//   listDoctors(newqueryParamsDoctor).then(response => {
//     console.log(response.rows)
//     return response.rows
//   })
// }
// 排班科室选择后，根据科室查询诊室列表
function getWorkTypeList() {
  listSchtype(newqueryParams).then(response => {
    // console.log(response)
    if(response.code == 200){
      workTypeList.value = response.rows
    } else {
      workTypeList.value = []
    }
  })
}

// 获取诊室列表@鲍小伟20251117
function getRoomList() {
  listConsultingroom({ kid: form.value.kid }).then(response => {
    // console.log(response)
    disabledRoomNo.value = false
    if(response.total >0 && response.code == 200){
      roomList.value = response.rows
    } else {
      roomList.value = []
      form.value.roomNo = null //没有就清空
    }
  })
}

// 获取科室列表@鲍小伟20251111
function getDepartmentList() {
  listDepartment(newqueryParams).then(response => {
    // console.log(response)
    if(response.code == 200){
      departmentList.value = response.rows
    } else {
      departmentList.value = []
    }
  })
}

/** 查询排班列表列表 数据 */
function getListNew() {
  loading.value = true
  listSchedules(queryParams.value).then(response => {
    console.log(response)
    schedulesList.value = response.rows
    loading.value = false
  })

}
/** 查询当月排班（阻塞式） */
async function getList() {
  loading.value = true
  const newQueryParams = {
    workDate: baseDate.value.format('YYYY-MM') //当前月的排班列表
  }
  try {
    const response = await listSchedules(newQueryParams)
    schedulesList.value = response.rows
  } finally {
    loading.value = false
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    workYear: null,
    workDate: null,
    workType: null,
    doctorCode: [], //穿梭框这里要赋值为空数据
    hospitalCode: null,
    kid: null,
    roomNo: null,
    maxPatient: null,
    bookedNum: null,
    workStatus: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    maxActivityMbq: null,
    suser: userStore.name,
    remark: null
  }
  proxy.resetForm("schedulesRef")
}

//新的搜索按钮@鲍小伟20251120
/** 搜索按钮操作 */
function handleQueryNew() {
  queryParams.value.pageNum = 1
    //查询医生的列表
    if(queryParams.value.workDate){
      mode.value = 'day'
      buildHeader()
    } else {
      mode.value = 'week'
      buildHeader()
    }
    getAllDoctorList()
    getListNew() //查询查询一下

}



/** 重置按钮操作 */
function resetQueryNew() {
  proxy.resetForm("queryRef")
  handleQueryNew()
}




/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}



/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加排班列表"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getSchedules(_id).then(response => {
    //处理一下格式问题
    form.value = response.data
    form.value.doctorCode = response.data.doctorCode?JSON.parse(response.data.doctorCode):[]
    form.value.suser = userStore.name //当前登录用户
    //需要获取一份诊室列表
    getRoomList()
    open.value = true
    title.value = "修改排班列表"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["schedulesRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        //处理一下格式问题
        form.value.doctorCode = JSON.stringify(form.value.doctorCode)
        //年份为日期选择前四位
        form.value.workYear = form.value.workDate.substring(0, 4)
        updateSchedules(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        //处理一下格式问题
        form.value.doctorCode = JSON.stringify(form.value.doctorCode)
        //年份为日期选择前四位
        form.value.workYear = form.value.workDate.substring(0, 4)
        addSchedules(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除排班列表编号为"' + _ids + '"的数据项？').then(function() {
    return delSchedules(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/schedules/export', {
    ...queryParams.value
  }, `schedules_${new Date().getTime()}.xlsx`)
}

// getList()
</script>
